<template>
  <Modal
    v-model="visible"
    title="选择数据库"
    width="70vw"
    footer-hide
    @on-cancel="cancel"
    class-name="sql-select"
  >
    <div class="flex overflow-hidden" style="height: 60vh">
      <div class="w-1/4 h-full p-4 bg-slate-100">
        <Input class="mb-3" search placeholder="搜索" />
        <Dropdown class="w-full" transfer>
          <Button type="primary" class="w-full">
            新建数据表
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <template #list>
            <DropdownMenu>
              <DropdownItem @click.stop="showAdd = true"
                >自定义数据表</DropdownItem
              >
              <DropdownItem>基于模板创建</DropdownItem>
            </DropdownMenu>
          </template>
        </Dropdown>
        <p
          class="p-2 mt-4 text-sm text-black rounded cursor-pointer bg-slate-200"
        >
          <Icon type="ios-paper" />资源库数据库
        </p>
      </div>
      <div class="w-3/4 h-full p-6 overflow-auto">
        <div class="flex items-center justify-between w-full mb-4" v-for="item in databaseList" :key="item.id">
          <div class="flex items-center flex-1 cursor-pointer">
            <img
              class="w-8 h-8 rounded"
              src="~@/assets/images/database_default.png"
              alt="database default"
            />
            <p class="flex-1 ml-3">{{item.name}}</p>
          </div>
          <Button size="small" @click="onSelect(item)">添加</Button>
        </div>
      </div>
    </div>
  </Modal>
  <CommonDialog title="新建数据表" v-model="showAdd">
    <Form ref="formEl" :model="formData" :rules="rules" label-position="top">
      <FormItem label="数据表名称" prop="name">
        <Input
          v-model="formData.name"
          maxlength="50"
          show-word-limit
          placeholder="请输入数据表名称"
          clearable
        ></Input>
      </FormItem>
      <FormItem label="数据表描述" prop="remake">
        <Input
          v-model="formData.remake"
          maxlength="100"
          show-word-limit
          type="textarea"
          :rows="4"
          placeholder="请介绍数据表的主要用途，让大语言模型更加理解此表的功能"
        />
      </FormItem>
    </Form>
    <template #footer>
      <Button @click="showAdd = false">取消</Button>
      <Button type="primary" @click="nextSubmit">确认</Button>
    </template>
  </CommonDialog>
  <CommonDialog
    title="新建数据表"
    v-model="showAddList"
    width="80vw"
    :confirmLoading="addLoading"
  >
    <div class="mb-2">
      <p class="mb-1 text-black">Table查询模式</p>
      <Select style="width: 200px" v-model="formData.type">
        <Option :value="1" label="单用户模式">
          <p>单用户模式</p>
          <p style="color: #999; font-size: 12px">
            开发者和用户只能对自己创建的数据进行操作。
          </p>
        </Option>
        <Option :value="2" label="多用户模式">
          <p>多用户模式</p>
          <p style="color: #999; font-size: 12px">
            开发者和用户能对所有人创建的数据进行操作，该模式仅在工作流节点中有效。
          </p>
        </Option>
      </Select>
    </div>
    <Form ref="formRef" :model="formData">
      <el-table :data="formData.sqlList" style="width: 100%">
        <el-table-column label="存储字段名称" prop="name" min-width="200px">
          <template #header>
            <p>存储字段名称 <span style="color: red">*</span></p>
          </template>
          <template #default="{ $index, row }">
            <span v-if="$index < 4">{{ row.name }}</span>
            <FormItem
              v-else
              :key="$index"
              :prop="'sqlList.' + $index + '.name'"
              :rules="{
                required: true,
                message: '存储字段名称不可为空',
                trigger: 'blur',
              }"
            >
              <Input
                v-model="row.name"
                placeholder="请输入"
                size="small"
              ></Input>
            </FormItem>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description" min-width="200px">
          <template #default="{ $index, row }">
            <span v-if="$index < 4">{{ row.description }}</span>
            <FormItem v-else :key="$index">
              <Input
                v-model="row.description"
                size="small"
                placeholder="字段描述"
                show-word-limit
                maxlength="300"
              ></Input>
            </FormItem>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" prop="type" min-width="120px">
          <template #default="{ $index, row }">
            <span v-if="$index < 4">{{ row.type }}</span>
            <FormItem
              v-else
              :key="$index"
              :prop="'sqlList.' + $index + '.type'"
              :rules="{
                required: true,
                message: '数据类型不可为空',
                trigger: 'change',
              }"
            >
              <Select v-model="row.type" transfer size="small">
                <Option
                  v-for="item in DEFAULT_TYPES"
                  :value="item"
                  :key="item"
                  >{{ item }}</Option
                >
              </Select>
            </FormItem>
          </template>
        </el-table-column>
        <el-table-column label="是否必要" prop="required">
          <template #default="{ $index, row }">
            <Switch
              v-if="$index < 4"
              v-model="row.required"
              disabled
              size="small"
            />
            <FormItem v-else :key="$index">
              <Switch v-model="row.required" size="small" />
            </FormItem>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <Icon
              class="cursor-pointer"
              size="20"
              type="ios-trash"
              @click="handleTableRemove(scope.$index)"
            ></Icon>
          </template>
        </el-table-column>
      </el-table>
    </Form>
    <Button icon="md-add" @click="handleTableAdd">新增</Button>
    <template #footer>
      <Button @click="showAddList = false">上一步</Button>
      <Button type="primary" @click="submit">确认</Button>
    </template>
  </CommonDialog>
</template>
<script setup>
import { ref } from 'vue';
import { Message } from 'view-ui-plus';
import { listTable, listTableField ,addDatabase } from '@/api/modules/flow';
import CommonDialog from '@/components/CommonDialog/index.vue';

const props = defineProps({});

const emit = defineEmits(['select']);

const DEFAULT_TYPES = ['String', 'Integer', 'Time', 'Number', 'Boolean'];

const visible = ref(false);
// 新建数据表
const showAdd = ref(false);
const showAddList = ref(false);
const addLoading = ref(false);
const selectData = ref([])
// 数据表表单
const formEl = ref(null);
const formRef = ref(null);
const formData = ref({
  name: '',
  remake: '',
  sqlList: [
    {
      name: 'id',
      description: '数据的唯一标识（主键）',
      type: 'Integer',
      required: false,
    },
    {
      name: 'sys_platform',
      description: '数据产生或使用的渠道',
      type: 'String',
      required: false,
    },
    {
      name: 'uuid',
      description: '用户唯一标识，由系统生成',
      type: 'String',
      required: false,
    },
    {
      name: 'bstudio_create_time',
      description: '数据插入的时间',
      type: 'Time',
      required: false,
    },
    { name: '', description: '', type: 'String', required: false },
  ],
});
const rules = ref({
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
});

const handleTableAdd = () => {
  formData.value.sqlList.push({
    name: '',
    description: '',
    type: 'String',
    required: false,
  });
};
const handleTableRemove = (index) => {
  if (index < 4) return;
  formData.value.sqlList.splice(index, 1);
};

/**
 * 提交表单
 */
const nextSubmit = async () => {
  let valid = await formEl.value.validate((valid, fild) =>
    valid ? valid : fild
  );
  if (!valid) return;
  try {
    await addDatabase({data: {name: formData.value.name, remake: formData.value.remake }});
    Message.success('新增成功');
    getDatabaseList();
    emit('submit');
  } finally {
    showAdd.value = false;
  }
};

const submit = async () => {
  let valid = await formRef.value.validate((valid, fild) =>
    valid ? valid : fild
  );
  if (!valid) return;
  addLoading.value = true;
  try {
    await addDatabase({data: {...formData.value, kbtype: props.kbtype }});
    selectData.value.push(formData.value)
    Message.success('新增成功');
    emit('submit');
  } finally {
    showAdd.value = false;
    showAddList.value = false;
    addLoading.value = false;
  }
};

const databaseList = ref([]);
const getDatabaseList = async() => {
  const { data } = await listTable();
  databaseList.value = data;
}
getDatabaseList()
const onSelect = async item =>{
  const { data } = await listTableField({data: {dbtableid: item.id}})
  emit('select', item, data);
  visible.value = false;
  Message.success('已添加');
}

const cancel = () => {
  visible.value = false;
};
const init = () => {
  visible.value = true;
};

defineExpose({
  init,
});
</script>
<style lang="scss">
.sql-select .ivu-modal-body {
  padding: 0 !important;
}
</style>
